//---------   Variable --------------------------- //
var id_counter = 1;
var prop;
var map_area;
var contextMenu;
var resizeRect;
var event;
var obj = {};
var mapLeft;
var mapTop;
var mapW;
var mapH;
var BASE_URL = "http://localhost/atlantis/";

jQuery(document).ready(function(){

 // -------------------------------- Fontions ---------------- //
    function log(ch){console.log(ch);}
    function base_url(url){
    	if(!url)
    		var url = "";
    	return BASE_URL  + url;
    }
    function creatRect(evt){
        var rect = $('<div id="id'+id_counter+'" class="rect"></div>');
        id_counter++;
        rect.css('left' , evt.pageX -  map_area.offset().left - 10  )
            .css('top' ,  evt.pageY - map_area.offset().top - 10 );
        
        rect.draggable({
            drag : function(evt){
                var r = $('.rect.active');
                var coords = calculCoords(r);
                var objRect = obj[ r.attr('id') ];
                objRect.coords =  coords.x +','+coords.y+','+coords.w+','+coords.h;
                prop.find('#coords').val(objRect.coords);
            },
            stop : function(){
            	
                    var coords = calculCoords(rect);
                    var objRect = obj[ rect.attr('id') ];
                    objRect.coords =  coords.x +','+coords.y+','+coords.w+','+coords.h;
                    prop.find('#coords').val(objRect.coords);
            },
            cancel : ".resize"
        });
        rect.css( 'position'  ,  'absolute');
        return rect;
    }
    
    
    function showProp( rect , evt ){
       if(!rect.hasClass('active'))
       {
    	   
    	    var objRect = obj[ rect.attr('id')];
	        prop.find('#title').val(objRect.title );
	        prop.find('#coords').val(objRect.coords );
	        tinymce.editors[0].setContent(objRect.desc );
	        
	        if(objRect.extern)
	        {
	        	prop.find('#extern-url').val(objRect.url );
	        	prop.find('#url').val('' );
	        }else{
	        	prop.find('#url').val(objRect.url );
	        	prop.find('#extern-url').val('' );
	        } 
       }
	    	

        if(!evt)
        {
            prop.css('position' , 'absolute').show();
            return;
        }
        
        var x = evt.pageX;
        var y = evt.pageY;
        
        if ( x + rect.width()  + prop.width() > map_area.offset().left + map_area.width())
        {
            x = x - prop.width() - 30  - rect.width() ;
            
        }
        else
        {
            if ( x - prop.width()  < map_area.offset().left);
                {
                    x = x + rect.width() + 30;
                }
        }
        
        prop.css('position' , 'absolute')
                .css('left' , x)
                .css('top' , y)
                .show();
    }
    
    
    function hideProp(){
        prop.hide();
    }
    
    
    function calculCoords(rect){
        
        var x  =   (rect.position().left >0 )?rect.position().left : 0;
        var y   =  (rect.position().top > 0 )?rect.position().top : 0 ;
        var o = {
            x :  x,
            y  : y ,
            w  : x + rect.width() +  2,
            h  : y + rect.height() + 2
        };
        return o;
    }
   
    function removeRect(rect){
        if(!rect.length ){
            return;
        }
        delete obj[rect.attr('id')];
        resizeRect = rect.find('.resize').clone(true);
        rect.remove();
    }

 //---------------------------- Traitement -----------------------------------//
        prop = $('.prop');
        prop.draggable({
        	handle: ".header" 
        });
        
        
        $('.prop .header a').click(function(){
            hideProp();
            return false;
        });
        
        document.oncontextmenu = function() {return false;};
        $(document).click(function(e)
        {
     
            if( e.button === 0 )
            {
                contextMenu.hide();
            }
        });
        
        map_area = $('.map-aera');
        mapLeft = map_area.offset().left;
        mapTop = map_area.offset().top;
        mapW = map_area.width();
        mapH = map_area.height();
        
        contextMenu = $('.context-menu');
        map_area.mousedown(function(e)
        { 
            event = e;
            if( e.button === 2 )
            { 
              var x = e.pageX;
              var y = e.pageY;
              contextMenu.css('left' , x + 5).css('top' , y).show();
              return false; 
            } 
        return true; 
      }); 
      
      
      resizeRect = $('.resize');
      $('#create-rect').click(function(evt)
      {
         var rect = creatRect(event);
         $('.rect.active').removeClass('active');
         
         map_area.append(rect);
         
         var coords = calculCoords(rect);
         obj[rect.attr('id')] = {
             url : "",
             type : "rect",
             title : "",
             extern : false,
             coords :  coords.x +','+coords.y+','+coords.w+','+coords.h,
             desc : ""
         };
         contextMenu.hide();
         showProp( rect , evt );
         rect.append(resizeRect.show()).addClass('active');
         
         rect.mousedown(function(e){
        	 if(!$(this).hasClass('active'))
        	 {
        		 $('.rect.active').removeClass('active');
        		 showProp(  $(this) );
        		 $(this).addClass('active').append(resizeRect.show());
        	 }
        	 else
        	 {
        		 showProp(  $(this) );
        	 }
         });
         
      });
      
      
      $('#delete-rect').click(function(){
          removeRect($('.rect.active'));
          contextMenu.hide();
          hideProp();
      });
      
      
      resizeRect.mousedown(function(){
          //$('.rect.active').draggable('disable');
          $(document).mousemove(function(evt){
	             var x0 = $('.rect.active').offset().left ;
	             var y0 = $('.rect.active').offset().top;
	              
	             $('.rect.active').css('width' , evt.pageX - x0 )
	                               .css('height' , evt.pageY - y0);
	             var r = $('.rect.active');        
	             var coords = calculCoords(r);
	             var objRect = obj[ r.attr('id') ];
	             objRect.coords =  coords.x +','+coords.y+','+coords.w+','+coords.h;
	             prop.find('#coords').val(objRect.coords);          
	          });
          
	        resizeRect.mouseup(function()
	         {
	            $(document).unbind('mousemove');
	            //$('.rect.active').draggable('enable');
	        }); 
	        
	        $(document).mouseup(function()
	         {
	            $(document).unbind('mousemove');
	            //$('.rect.active').draggable('enable');
	        }); 
        
      });
      
      $('.prop #savebtn').click(function(){
         var o = obj[$('.rect.active').attr('id')]; 
         o.title = $('.prop #title').val() || "" ;
         
         
         if( $.trim( $('#extern-url').val() ).length != 0 ){
        	 o.extern = true;
        	 o.url = $('.prop #extern-url').val();
         }
         else 
        if( $('.prop #url').val() ){
        		 o.url = $('.prop #url').val();
        } 
        else{
        	alert('Le champ url ne peut pas être vide !');
       	 	return;	 
        }
         
         tinyMCE.triggerSave();
         o.desc = $('.prop #desc').val();
         
         hideProp();
      });
      
     
      
      $('.prop #cancelbtn').click(function(){
          hideProp();
          removeRect($('.rect.active'));
          
      });


      $('#delete-all').click(function(){

    	  if(confirm("Etes-vous sûre de vouloir supprimer tous les Rectongles ?"))
    	  {
    		  resizeRect = $('.resize').clone(true);
	    	  $('.map-aera .rect').remove();
	    	  obj = {};
	    	  hideProp();
    	  } 
      });
      
      // ---------------  Sauvgarde des Donnees -------------------
      
      $('#save-all').click(function(){
    	  var msg = {
    			  img_id : map_area.data('img-id'),
    			  coords : obj 
    	  };
    	  
    	  jQuery.ajax({
    		  url	: base_url('image_map/save_map'),
    		  type	: "POST",
    		  data	: { content : JSON.stringify(msg ) },
    		  success: function(response, textStatus, jqXHR) 
    		  {
    			if(response !== "success"){
    				alert("Une Erreur s'est produite, merci de contactez votre admin !" );
    			}  
    		  },
    		  error : function(){
    			  alert('Une erreur s\'est produite merci de ressayer !');
    		  },
    		 beforeSend : function(){
    			 $('#save-all').html('Encours...').attr("disabled", "disabled");
    		 },
    		 complete : function(){
    			  $('#save-all').html('Envoyer').removeAttr("disabled");
    		  }
    	});
      });
       
      
      // tinymce html editor
      tinymce.init({
          selector: ".prop #desc",
//          plugins : 'advlist  autolink autoresize autosave bbcode charmap   contextmenu directionality emoticons  fullpage fullscreen hr  insertdatetime layer legacyoutput link lists importcss media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor visualblocks visualchars wordcount',
//          toolbar: "forecolor backcolor"	  
       });

});